﻿using System.Net.Sockets;
using System.Net;
using System;
using System.Text;
using System.Threading;
using System.IO;

using System.Drawing;
using System.Drawing.Imaging;
using System.Windows;
using System.Windows.Media.Imaging;

namespace MulticastPictureReceiver
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;

        // The address of the multicast group to join.
        // Must be in the range from 224.0.0.0 to 239.255.255.255
        private const string GROUP_ADDRESS = "224.0.1.11";

        // The port over which to communicate to the multicast group
        private const int GROUP_PORT = 54329;

        private const int MAX_SIZE_H = 123;
        private const int MAX_SIZE_W = 164;
        private const int MAX_MESSAGE_SIZE = 1024;

        private const int OWN_BYTES_COUNT = 3;
        private int receivedPictureIndex = 0;
        private int receivedMaxBlockCount = 0;

        UdpClient client = new UdpClient();

        Thread thread = null;
        bool threadPleaseExit;

        MemoryStream readingMemoryStream = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(249, 159);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(164, 123);
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.BackColor = System.Drawing.Color.Transparent;
            this.label1.Location = new System.Drawing.Point(12, 285);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(187, 13);
            this.label1.TabIndex = 1;
            this.label1.Text = "Tero Paananen tepaanan@gmail.com";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.BackColor = System.Drawing.Color.Transparent;
            this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(12, 9);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(340, 31);
            this.label2.TabIndex = 2;
            this.label2.Text = "Multicast Camera Receiver";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(482, 272);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 3;
            this.button1.Text = "Exit";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackgroundImage = global::MulticastPictureReceiver.Properties.Resources.Free_Apple_Wallpapers_Survelence_Camera;
            this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            this.ClientSize = new System.Drawing.Size(569, 307);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.pictureBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion


        protected void StartThread()
        {
            Console.WriteLine("StartThread");
            threadPleaseExit = false;
            thread = new Thread(startUDP);
            thread.Start();
        }

        protected void StopThread()
        {
            Console.WriteLine("StopThread");
            threadPleaseExit = true;
            if (thread != null)
            {
                Console.WriteLine("Closing...");
                thread.Abort();
                client.Close();
                Console.WriteLine("OK");
            }

        }

        private void startUDP()
        {
            IPEndPoint localEp = new IPEndPoint(IPAddress.Any, GROUP_PORT);
            client.Client.Bind(localEp);

            IPAddress multicastaddress = IPAddress.Parse(GROUP_ADDRESS);
            client.JoinMulticastGroup(multicastaddress);

            Console.WriteLine("UDP listening");
            while (!threadPleaseExit)
            {
                byte[] data = client.Receive(ref localEp);
                ProcessReceivedBytes(data);
            }
        }

        void CleanMemoryStream(ref MemoryStream stream)
        {
            byte[] b = new byte[stream.Capacity];
            stream.Position = 0;
            stream.Write(b, 0, b.Length);
            stream.Flush();
        }

        void ProcessReceivedBytes(byte[] bytes)
        {
            bool firstBytes = false;
            if (readingMemoryStream == null)
            {
                firstBytes = true;
                readingMemoryStream = new MemoryStream();
                this.receivedMaxBlockCount = (int)bytes[bytes.Length - 3];
                this.receivedPictureIndex = (int)bytes[bytes.Length - 2];
                CleanMemoryStream(ref readingMemoryStream);
            }

            int blokIndex = (int)bytes[bytes.Length - 1];
            int pictureIndex = (int)bytes[bytes.Length - 2];
            int blokMaxCount = (int)bytes[bytes.Length - 3];
            Console.WriteLine("Received: block " + blokIndex + "/" + blokMaxCount + ", pictureIndex " + pictureIndex);

            // New picture received
            // Show previous if we have it whole
            if (pictureIndex != this.receivedPictureIndex)
            {
                if (this.receivedMaxBlockCount <= 0 && !firstBytes)
                {
                    try
                    {
                        readingMemoryStream.Flush();
                        Image bmp = System.Drawing.Image.FromStream(readingMemoryStream);
                        this.pictureBox1.Image = bmp;
                    }
                    catch
                    {
                        Console.WriteLine("ERROR");
                    }
                }
                CleanMemoryStream(ref readingMemoryStream);
                this.receivedMaxBlockCount = blokMaxCount;
            }

            // Store received picture binary
            this.receivedPictureIndex = pictureIndex;
            this.receivedMaxBlockCount--;
            if (blokIndex == 1)
            {
                readingMemoryStream.Position = 0;
            }
            else
            {
                readingMemoryStream.Position = ((blokIndex - 1) * (MAX_MESSAGE_SIZE - OWN_BYTES_COUNT - 1));
            }
            readingMemoryStream.Write(bytes, 0, bytes.Length - OWN_BYTES_COUNT);
        }


        Bitmap GetBitmap(BitmapSource source)
        {
            Bitmap bmp = new Bitmap(
              source.PixelWidth,
              source.PixelHeight,
              PixelFormat.Format32bppPArgb);
            BitmapData data = bmp.LockBits(
              new Rectangle(new System.Drawing.Point(0,0), bmp.Size),
              ImageLockMode.WriteOnly,
              PixelFormat.Format32bppPArgb);
            source.CopyPixels(
              Int32Rect.Empty,
              data.Scan0,
              data.Height * data.Stride,
              data.Stride);
            bmp.UnlockBits(data);
            return bmp;
        }




        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button button1;
    }
}

